#include "../common/dispatcher.hpp"
#include "../server/rpc_router.hpp"

// void onRpcRequest(const Json_rpc::BaseConnection::ptr &conn, Json_rpc::RpcRequest::ptr &msg)
// {
//     std::cout << "收到rpc请求" << std::endl;
//     std::string body = msg->serialize();
//     std::cout << body << std::endl;
//     auto rpc_req = Json_rpc::MessageFactory::create<Json_rpc::RpcResponse>();
//     rpc_req->setId(Json_rpc::UuidUtil::uuid());
//     rpc_req->setRCode(Json_rpc::RCode::RCODE_OK);
//     rpc_req->setMType(Json_rpc::MType::REP_RPC);
//     rpc_req->setResult(33);
//     conn->send(rpc_req);
// }
// void onTopicRequest(const Json_rpc::BaseConnection::ptr &conn, Json_rpc::TopicRequest::ptr &msg)
// {
//     std::cout << "收到topic请求" << std::endl;
//     std::string body = msg->serialize();
//     std::cout << body << std::endl;
//     auto rpc_req = Json_rpc::MessageFactory::create<Json_rpc::TopicResponse>();
//     rpc_req->setId(Json_rpc::UuidUtil::uuid());
//     rpc_req->setRCode(Json_rpc::RCode::RCODE_OK);
//     rpc_req->setMType(Json_rpc::MType::REP_TOPIC);
//     conn->send(rpc_req);
// }

void Add(const Json::Value &req,Json::Value &rsp)
{
    int num1=req["num1"].asInt();
    int num2=req["num2"].asInt();
    rsp=num1+num2;
}

int main()
{

    // dispatcher->registerHandler<Json_rpc::RpcRequest>(Json_rpc::MType::REQ_RPC, onRpcRequest);       // 注册映射关系
    // dispatcher->registerHandler<Json_rpc::TopicRequest>(Json_rpc::MType::REQ_TOPIC, onTopicRequest); // 注册映射关系

    auto router = std::make_shared<Json_rpc::server::RpcRouter>();

    std::unique_ptr<Json_rpc::server::SDescribeFacyory> desc_factory(new Json_rpc::server::SDescribeFacyory);

    desc_factory->setMethodName("Add");
    desc_factory->setParamsDesc("num1",Json_rpc::server::VType::INTEGRAL);
    desc_factory->setParamsDesc("num2",Json_rpc::server::VType::INTEGRAL);
    desc_factory->setReturnType(Json_rpc::server::VType::INTEGRAL);
    desc_factory->setCallback(Add);
    router->registerMethod(desc_factory->build());

    auto cb = std::bind(&Json_rpc::server::RpcRouter::onRpcRequest,router.get(),std::placeholders::_1,std::placeholders::_2);
   
    auto dispatcher = std::make_shared<Json_rpc::Dispatcher>();

    dispatcher->registerHandler<Json_rpc::RpcRequest>(Json_rpc::MType::REQ_RPC,cb);

    auto server = Json_rpc::ServerFactory::create(9090);

    auto message_cb = std::bind(&Json_rpc::Dispatcher::onMessage, dispatcher.get(),std::placeholders::_1, std::placeholders::_2);

    server->setMessageCallback(message_cb);
    server->start();
    return 0;
}